<template>
  <div class="app-container" :style="windowWidth < 1080 ? 'background-color: #f6f8f9;' : ''">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      :label-width="windowWidth < 1080 ? '100px' : '68px'"
      :style="windowWidth < 1080 ? 'background-color: #fff;padding: 20px 20px 0;' : ''">
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="系统/商户/官方订单号" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="充值账号" prop="accountName">
        <el-input v-model="queryParams.accountName" placeholder="昵称/抖音ID " clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="支付方式" prop="payment">
        <el-select v-model="queryParams.payment" placeholder="请选择支付方式" clearable size="small">
          <el-option label="微信" value="1" />
          <el-option label="支付宝" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="tradeStatus">
        <el-select v-model="queryParams.tradeStatus" placeholder="请选择订单状态" clearable size="small">
          <el-option label="成功" value="0" />
          <el-option label="未付" value="1" />
          <el-option label="超时" value="2" />
          <el-option label="失败" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="通知状态" prop="notifyStatus">
        <el-select v-model="queryParams.notifyStatus" placeholder="请选择通知状态" clearable size="small">
          <el-option label="成功" value="0" />
          <el-option label="等待" value="1" />
          <el-option label="失败" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="账号分组" prop="groupId">
        <el-select v-model="queryParams.accountGroupId" placeholder="请选择所属账号分组" size="small" clearable>
          <el-option v-for="item in accountGroupList" :key="item.groupId" :label="item.groupName"
            :value="item.groupId" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单分组" prop="groupId">
        <el-select v-model="queryParams.groupId" placeholder="请选择所属订单分组" size="small" clearable>
          <el-option v-for="item in tradeGroupList" :key="item.groupId" :label="item.groupName" :value="item.groupId" />
        </el-select>
      </el-form-item>
      <!--       <el-form-item label="充值账号" prop="accountName">
        <el-input v-model="queryParams.accountName" placeholder="抖音ID/名称/CK" clearable size="small" />
      </el-form-item> -->
      <el-form-item label="创建时间" v-if="windowWidth > 1080">
        <el-date-picker v-model="daterangeCreateTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="createDefaultTime"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置条件</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8"
      :style="windowWidth < 1080 ? 'background-color: #fff;margin:0;padding:0 15px 20px;' : ''">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-mouse" size="mini" :disabled="multiple" @click="handleSupplement">
          批量补单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-mouse" size="mini" :disabled="multiple"
          @click="handleManualNotice">
          批量通知</el-button>
      </el-col>
      <el-col :span="1.5" v-if="windowWidth > 1080">
        <el-button type="primary" plain icon="el-icon-download" size="mini" :loading="exportLoading"
          @click="handleExport" v-hasPermi="['merchant:trade:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tradeList" @selection-change="handleSelectionChange" ref="tableDateRef">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column label="订单编号" align="left" prop="tradeNo" :show-overflow-tooltip="true"
        v-if="columns[0].visible && windowWidth >1080" :key="Math.random()" />
      <el-table-column label="订单编号" align="left" prop="tradeNo" width="150" fixed="left"
        v-if="columns[0].visible && windowWidth <1080" :key="Math.random()" />
      <el-table-column label="抖音ID" width="120" align="left" prop="douyinId" v-if="columns[1].visible" :key="Math.random()" />
      <el-table-column label="账号名称" align="left" width="100" prop="accountName" v-if="columns[2].visible" :key="Math.random()" />
      <el-table-column label="头像" align="left" prop="avatar" v-if="columns[3].visible" :key="Math.random()">
        <template slot-scope="scope">
          <el-image style="width:50px;height:50px;" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" />
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="left" prop="payment" v-if="columns[4].visible" :key="Math.random()">
        <template slot-scope="scope">
          <span v-if="scope.row.payment == 1">微信</span>
          <span v-if="scope.row.payment == 2">支付宝</span>
        </template>
      </el-table-column>
      <el-table-column label="所属核销" align="left" prop="userName" width="80" v-if="columns[15].visible" :show-overflow-tooltip="true" :key="Math.random()" />
      <el-table-column label="所属通道" align="left" prop="channelName" width="200" v-if="columns[5].visible" :key="Math.random()" />
      <el-table-column label="账号分组" align="left" width="100" prop="accountGroupName" v-if="columns[6].visible" :key="Math.random()" />
      <el-table-column label="订单分组" align="left" prop="tradeGroupName" v-if="columns[7].visible" :key="Math.random()" />
      <el-table-column label="金额" align="left" prop="amount" v-if="columns[8].visible" :key="Math.random()" />
      <el-table-column label="商户订单号" align="left" width="90" prop="outTradeNo" :show-overflow-tooltip="true"
        v-if="columns[9].visible" :key="Math.random()" />
      <el-table-column label="官方订单号" align="left" width="90" prop="officialTradeNo" :show-overflow-tooltip="true"
        v-if="columns[10].visible" :key="Math.random()" />
      <el-table-column label="交易单号" align="left" prop="officialOutTradeNo" :show-overflow-tooltip="true"
        v-if="columns[11].visible" :key="Math.random()" />
      <el-table-column label="订单状态" align="left" width="100" prop="tradeStatus" v-if="columns[12].visible" :key="Math.random()">
        <template slot-scope="scope">
          <span style="color:#fff;padding:0px 8px;background:#67C23A;border-radius: 10px;display: inline-block;"
            v-if="scope.row.tradeStatus == 0">成功</span>
          <span style="color:#fff;padding:0px 8px;background:#909399;border-radius: 10px;display: inline-block;"
            v-if="scope.row.tradeStatus == 1">未付</span>
          <span style="color:#fff;padding:0px 8px;background:#E6A23C;border-radius: 10px;display: inline-block;"
            v-if="scope.row.tradeStatus == 2">超时</span>
          <el-tooltip placement="top" :content="scope.row.failureReason" v-if="scope.row.tradeStatus == 3">
            <span v-if="scope.row.tradeStatus == 3"
              style="color:#fff;padding:0px 8px;background:#F56C6C;border-radius: 10px;display: inline-block;cursor: pointer;">失败</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="通知状态" align="center" width="100" prop="notifyStatus" v-if="columns[13].visible" :key="Math.random()">
        <template slot-scope="scope">
          <span style="color:#fff;padding:0px 8px;background:#67C23A;border-radius: 10px;display: inline-block;"
            v-if="scope.row.notifyStatus == 0">成功</span>
          <span style="color:#fff;padding:0px 8px;background:#909399;border-radius: 10px;display: inline-block;"
            v-if="scope.row.notifyStatus == 1">等待</span>
          <span style="color:#fff;padding:0px 8px;background:#F56C6C;border-radius: 10px;display: inline-block;"
            v-if="scope.row.notifyStatus == 2">失败</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" prop="createTime" width="150" v-if="columns[14].visible" :key="Math.random()" />
      <!-- <el-table-column label="备注" align="left" prop="remark" /> -->
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right" width="200"
        v-if="windowWidth > 1080">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-mouse" @click="handleSupplement(scope.row)"
            v-if="scope.row.tradeStatus != 0">手动补单</el-button>
          <el-button size="mini" type="text" icon="el-icon-mouse" @click="handleManualNotice(scope.row)"
            v-if="scope.row.notifyStatus != 0">手动通知</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="200"
        v-if="windowWidth < 1080">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-mouse" @click="handleSupplement(scope.row)"
            v-if="scope.row.tradeStatus != 0">手动补单</el-button>
          <el-button size="mini" type="text" icon="el-icon-mouse" @click="handleManualNotice(scope.row)"
            v-if="scope.row.notifyStatus != 0">手动通知</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" style="height:57px;" />

  </div>
</template>

<script>
  import {
    listTrade,
    getTrade,
    delTrade,
    addTrade,
    updateTrade,
    supplement,
    manualNotice
  } from "@/api/merchant/trade";

  import {
    listChannel
  } from "@/api/merchant/channel"


  import {
    listAccountGroup
  } from "@/api/merchant/accountGroup";


  import {
    listTradeGroup,
  } from "@/api/merchant/tradeGroup";

  export default {
    name: "Trade",
    data() {
      return {
        createDefaultTime: ['00:00:00', '23:59:59'],
        minDate: '',
        maxDate: '',
        pickerOptions: {
          onPick: ({
            maxDate,
            minDate
          }) => {
            this.minDate = minDate
            this.maxDate = maxDate
          },
          disabledDate: (time) => { //查询时间跨度为1天
            if (this.minDate) {
              let range = 1 * 24 * 3600 * 1000
              return time.getTime() > (this.minDate.getTime() + range) || time
                .getTime() < (this.minDate.getTime() - range)
            }
            return time.getTime() > Date.now()
          }
        },
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 订单信息表格数据
        tradeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 备注时间范围
        daterangeCreateTime: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userId: undefined,
          accountId: undefined,
          channelId: undefined,
          groupId: undefined,
          amount: undefined,
          outTradeNo: undefined,
          officialTradeNo: undefined,
          tradeStatus: undefined,
          notifyStatus: undefined,
          returnUrl: undefined,
          notifyUrl: undefined,
          expiryTime: undefined,
          createTime: undefined,
        },
        // 表单参数
        form: {},
        //账号分组列表
        accountGroupList: [],
        //订单分组列表
        tradeGroupList: [],
        //通道列表
        channelList: [],
        // 表单校验
        rules: {},
        // 列信息
        columns: [{
            key: 0,
            label: `订单编号`,
            visible: true
          },
          {
            key: 1,
            label: `抖音ID`,
            visible: true
          },
          {
            key: 2,
            label: `账号名称`,
            visible: true
          },
          {
            key: 3,
            label: `头像`,
            visible: true
          },
          {
            key: 4,
            label: `支付方式`,
            visible: true
          },
          {
            key: 5,
            label: `所属通道`,
            visible: true
          },
          {
            key: 6,
            label: `账号分组`,
            visible: true
          },
          {
            key: 7,
            label: `订单分组`,
            visible: true
          },
          {
            key: 8,
            label: `金额`,
            visible: true
          },
          {
            key: 9,
            label: `商户订单号`,
            visible: true
          },
          {
            key: 10,
            label: `官方订单号`,
            visible: true
          },
          {
            key: 11,
            label: `交易单号`,
            visible: true
          },
          {
            key: 12,
            label: `订单状态`,
            visible: true
          },
          {
            key: 13,
            label: `通知状态`,
            visible: true
          },
          {
            key: 14,
            label: `创建时间`,
            visible: true
          },
          {
            key: 15,
            label: `所属核销`,
            visible: true
          },
        ],
        windowWidth: document.documentElement.clientWidth, //实时屏幕宽度
      };
    },
    created() {
      this.getList();
      //账号分组列表
      listAccountGroup().then(response => {
        this.accountGroupList = response.rows;
      });
      //订单分组列表
      listTradeGroup().then(response => {
        this.tradeGroupList = response.rows;
      });
      //通道列表
      listChannel(0).then(response => {
        this.channelList = response.data;
      })
    },
    beforeUpdate() {
       this.$nextTick(() => {
         this.$refs.tableDateRef.doLayout()
       })
    },
    methods: {
      /** 查询订单信息列表 */
      getList() {
        this.loading = true;
        this.queryParams.params = {};
        if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
          this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
          this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
        }
        listTrade(this.queryParams).then(response => {
          this.tradeList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.$nextTick(() => {
            this.$refs.tableDateRef.doLayout()
          })
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          tradeNo: undefined,
          userId: undefined,
          accountId: undefined,
          channelId: undefined,
          groupId: undefined,
          amount: undefined,
          outTradeNo: undefined,
          officialTradeNo: undefined,
          tradeStatus: "0",
          notifyStatus: "0",
          returnUrl: undefined,
          notifyUrl: undefined,
          expiryTime: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.daterangeCreateTime = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.tradeNo)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加订单信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const tradeNo = row.tradeNo || this.ids
        getTrade(tradeNo).then(response => {
          this.loading = false;
          this.form = response.data;
          this.open = true;
          this.title = "修改订单信息";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.tradeNo != null) {
              updateTrade(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addTrade(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const tradeNos = row.tradeNo || this.ids;
        this.$modal.confirm('是否确认删除订单信息编号为"' + tradeNos + '"的数据项？').then(() => {
          this.loading = true;
          return delTrade(tradeNos);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.$download.excel('trade/export', this.queryParams);
      },
      //手动补单
      handleSupplement(row) {
        const tradeNos = row.tradeNo || this.ids;
        this.$prompt('请输入密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: function(val) {
            if (val == null || val == '' || val == 'null') {
              return false;
            }else {
              return true;
            }
          },
          inputErrorMessage: '密码不能为空'
        }).then(({ value }) => {
          this.loading = true;
          return supplement(tradeNos, value);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("补单成功");
        }).finally(() => {
          this.loading = false;
        });
        // this.$modal.confirm('是否确认手动补单编号为"' + tradeNos + '"的数据项？').then(() => {
        //   this.loading = true;
        //   return supplement(tradeNos);
        // }).then(() => {
        //   this.loading = false;
        //   this.getList();
        //   this.$modal.msgSuccess("补单成功");
        // }).finally(() => {
        //   this.loading = false;
        // });
      },
      //手动通知
      handleManualNotice(row) {
        const tradeNos = row.tradeNo || this.ids;
        this.$modal.confirm('是否确认手动通知编号为"' + tradeNos + '"的数据项？').then(() => {
          this.loading = true;
          return manualNotice(tradeNos);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("通知补发成功");
        }).finally(() => {
          this.loading = false;
        });
      },
    }
  };

</script>
<style scoped>
  ::v-deep .el-checkbox__inner {
    width: 20px;
    height: 20px;
  }

  ::v-deep .el-checkbox__inner::after {
    top: 2px;
    height: 10px;
    left: 7px;
  }

  .choice {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .choice-item {
    padding: 8px 8px;
    border: 1px solid #999;
    border-radius: 4px;
    margin-right: 20px;
    margin-bottom: 20px;
    cursor: pointer;
  }

</style>
